<template>
  <el-dialog
    :title="formData.id ? '编辑员工' : '新增员工'"
    :visible="showDialog"
    @close="closeFn"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="submit">添加</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
<script>
import { addEmployees, getEmployeess, editEmployees } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        username: '',
        email: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '角色名称不能为空！', trigger: 'blur' },
          { min: 1, max: 10, message: '角色名称长度1到10位!', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '密码不能为空！', trigger: 'blur' },
          { min: 1, max: 10, message: '密码长度1到10位!', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 调用接口
    async getEmployeess(id) {
      const res = await getEmployeess(id)
      // 数据回显
      this.formData = res.data
    },
    // 添加按钮
    submit() {
      // 表单校验 --- 校验同调用接口
      this.$refs.form.validate(async bool => {
        if (bool) {
          if (this.formData.id) {
            await editEmployees(this.formData)
          } else {
            await addEmployees(this.formData)
          }
          //   关闭弹窗
          //  子组件不能直接修改父组件元素，这样会导致父子组件数据不一致
          //   this.showDialog = false
          // 所以我们需要通过子传父技术通知父组件修改showDialog的值
          this.closeFn()
          // 更新浏览器中显示的列表
          this.$emit('updateEvent')
        }
      })
    },
    // 关闭弹框
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空表单
      this.formData = {
        username: '',
        email: '',
        password: ''
      }
      // 清空校验规则
      this.$refs.form.resetFields()
    }
  }
}
</script>
  <style lang="scss">
  .el-dialog__header {
      background: #66b1ff;

      .el-icon-close:before {
        color: #fff;
      }

      .el-dialog__title {
        color: #fff;
      }

    }
  </style>

